package com.hxh.learn.config;

import cn.hutool.json.JSONUtil;
import com.hxh.common.unification.ResultOutcome;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: hxh
 * @Date: 2023/3/3
 */
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        //设置返回json
        httpServletResponse.setContentType("application/json;charset=utf-8");
        ServletOutputStream stream = httpServletResponse.getOutputStream();
        String message = e.getMessage();
        if (e instanceof BadCredentialsException){
            message="账户或密码错误";
        }
        stream.write(JSONUtil.toJsonStr(ResultOutcome.fileResult(message)).getBytes("UTF-8"));
        stream.flush();
        stream.close();
    }
}
